﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using BusinessLogic;
using Domain.Entities;
using Web.Models;

namespace Web.Controllers
{
    public class AccountController : Controller
    {
        private DataManager dataManager;
        public AccountController(DataManager dataManager)
        {
            this.dataManager = dataManager;
        }
        // вход на сайт
        public ActionResult Index()
        {
            ViewData["Dish"] = dataManager.Dishes.GetDishesAll();
            return View();//dataManager.Dishes.GetDishesAll()
        }

        [HttpPost]
        public ActionResult Index(LoginViewModel model)
        {
            ViewData["Dish"] = dataManager.Dishes.GetDishesAll();    
            if (ModelState.IsValid)
                {
                    if (dataManager.MembershipProvider.ValidateUser(model.UserName,
                                        model.Password))
                    {
                        TempData["UsName"] = model.UserName;
                        TempData["UsPas"] = model.Password;
                        User us = dataManager.Users.GetUser(model.UserName, model.Password);
                        int role = us.RoleID;
                        FormsAuthentication.SetAuthCookie(model.UserName, false); //устанавливаем соответсвущие куки
                        return RedirectToAction("Index", "Home");
                        //switch (role)
                        //{
                        //    case 1: return RedirectToAction("Admin", "Home");
                        //        break;
                        //    case 2: return RedirectToAction("Manager", "Home");
                        //        break;
                        //    default: return RedirectToAction("Index", "Home");
                        //      break;  
                        //}
                    }
                    ModelState.AddModelError("",
                        "Ошибка! Введены неверные данные для входа.");
                }
                return View(model);            
        }

        // !!!регистрация  
        public ActionResult Registration()
        {
            ViewData["Dish"] = dataManager.Dishes.GetDishesAll();
            ViewBag.Depart = dataManager.Departments.GetDepartments();
            return View();
        }

        [HttpPost]
        public ActionResult Registration(RegistrationViewModel m)
        {
            ViewData["Dish"] = dataManager.Dishes.GetDishesAll();
            ViewBag.Depart = dataManager.Departments.GetDepartments();
           
            if (ModelState.IsValid)
            {
                int dID = 0;
                dID = Convert.ToInt32(m.SelectedDepartment.ID);//SelectedDepartment
                if (dID != 0)
                {
                    MembershipCreateStatus statusProfile = 
                         dataManager.MembershipProvider.CreateProfile(
                         m.FirstName, m.MiddleName, m.LastName, m.PersNo, m.Phone,dID);
                    if (statusProfile != MembershipCreateStatus.Success)
                    {
                        ModelState.AddModelError("",GetMembershipCreateStatusResultText(statusProfile));
                        return View(m);
                    }
                    
                    int roleId = 3;// обычный пользователь                   
                     int profileId = dataManager.MembershipProvider.GetProfilePersNo(
                         m.PersNo.ToString());
                    
                     MembershipCreateStatus statusUser = 
                         dataManager.MembershipProvider.CreateUser(
                         m.UserName, m.Password, profileId,roleId);

                     if ((statusProfile == MembershipCreateStatus.Success) &&
                         (statusUser == MembershipCreateStatus.Success))                       
                         return View("Success");
                     
                     ModelState.AddModelError("", GetMembershipCreateStatusResultText(statusUser));  
                 }
            }
            return View(m);
        }

        //Создаем текст ошибки для MembershipCreateStatus
        public string GetMembershipCreateStatusResultText(MembershipCreateStatus status)
        {
            if (status == MembershipCreateStatus.DuplicateUserName)
                return "Пользователь с таким логином уже существует";
            if (status == MembershipCreateStatus.ProviderError)
                return "Пользователь с таким табельным номером уже существует";
            return "Неизвестная ошибка";
        }

        //public ActionResult Logout()
        //{
        //    FormsAuthentication.SignOut(); // завершаем работу
        //    return RedirectToAction("Index"); // перенаправляем
        //}

    }      
}
